package com.sync.hkmjsyncdata.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkEventRecord;
import com.sync.hkmjsyncdata.service.IHkEventRecordService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SyncMjEventRecord {


    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;


    @Resource
    IHkEventRecordService eventRecordService;

    //{"code":"0","msg":"success","data":{"pageSize":10,"list":[{"eventId":"2795fd58b0b19460d31b63ce69420ac0","eventName":"acs.acs.eventType.infoDoorLockClose","eventTime":"2025-06-26T10:21:56+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199942,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:21:59.222+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"6cd4e01fb72c45a57dda9ea7b1557a91","eventName":"acs.acs.eventType.infoDoorLockOpen","eventTime":"2025-06-26T10:21:51+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199941,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:21:53.180+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"d687d137b1ea26dda6ea5510b13c37e4","eventName":"acs.acs.eventType.successFace","eventTime":"2025-06-26T10:21:51+08:00","personId":"1","cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":"/pic?0da300=0fa0ip-1fo471-a25*0o6=0=0555*2l9415019107*5t1=8*6ps==113b*=31c7*1d557b944-9914d0-0*l1ceod03132=00c","svrIndexCode":"346bfc19-9bcc-4063-ac60-ca248cd53964","eventType":196893,"inAndOutType":1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:21:53.107+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"23051234ecc56057ceefee870340fdfd","eventName":"acs.acs.eventType.infoDoorLockClose","eventTime":"2025-06-26T10:19:45+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199942,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:19:48.390+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"9cfe3f70a63649742d8a7137735e1742","eventName":"acs.acs.eventType.infoDoorLockOpen","eventTime":"2025-06-26T10:19:40+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199941,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:19:42.353+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"5017311fcecee9fd753f3cd2390d8c2b","eventName":"acs.acs.eventType.successFace","eventTime":"2025-06-26T10:19:40+08:00","personId":"1","cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":"/pic?0da300=0fa0ip-1fo711-a65*0o5=4=3597*2l1433089107*5t1=8*5ps==113b*=31c7*1d557b944-9913d0-2*l1ceod03132=00c","svrIndexCode":"346bfc19-9bcc-4063-ac60-ca248cd53964","eventType":196893,"inAndOutType":1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:19:42.297+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"489359bc8275cbb32edc7c9fca135334","eventName":"acs.acs.eventType.infoDoorLockClose","eventTime":"2025-06-26T10:18:32+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199942,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:18:35.222+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"ed4d0da54dbc1922ff10d8b05cb87c0b","eventName":"acs.acs.eventType.infoDoorLockOpen","eventTime":"2025-06-26T10:18:27+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199941,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:18:29.162+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"92b126f4d7f33799a04c90a28b6f9169","eventName":"acs.acs.eventType.successFace","eventTime":"2025-06-26T10:18:27+08:00","personId":"1","cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":"/pic?0da300=0fa0ip-1fo251-a55*0o0=4=1690*8l8463009107*5t1=8*4ps==113b*=31c7*1d557b944-9903d0-2*l1ceod03132=00c","svrIndexCode":"346bfc19-9bcc-4063-ac60-ca248cd53964","eventType":196893,"inAndOutType":1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:18:29.091+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null},{"eventId":"4583bdec3928d483479b082df86b371d","eventName":"acs.acs.eventType.infoDoorLockClose","eventTime":"2025-06-26T10:17:25+08:00","personId":null,"cardNo":null,"personName":null,"orgIndexCode":null,"orgName":null,"doorName":"运行管理中心大门口","doorIndexCode":"0a47727b5eaf43928f17737cfe243973","doorRegionIndexCode":"root000000","picUri":null,"svrIndexCode":null,"eventType":199942,"inAndOutType":-1,"readerDevIndexCode":"3e896d08ae8948718c95387c93d8c374","readerDevName":"读卡器_1","devIndexCode":"bb147c3574e24ff9b085e6469f9725cd","devName":"运行管理中心大门口","identityCardUri":null,"receiveTime":"2025-06-26T10:17:27.799+08:00","jobNo":null,"studentId":null,"certNo":null,"temp":null}],"total":3625,"totalPage":363,"pageNo":1}}


    /**
     * 同步海康人员
     */
    @XxlJob("SyncMjEventRecord")
    public void SyncMjEventRecordData() {
        XxlJobHelper.log("开始同步海康门禁人员打卡记录信息");
        LambdaQueryWrapper<HkEventRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(HkEventRecord::getUpdateTime).last(" limit 1");
        HkEventRecord record = eventRecordService.getOne(queryWrapper, false);
        String bgDate = LocalDate.now().minusDays(7).toString();
        String receiveStartTime = convertDateTimeFormatto(bgDate + " 00:00:00");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (ObjectUtils.isNotEmpty(record) && ObjectUtils.isNotEmpty(record.getEntranceDate())) {
            receiveStartTime = convertDateTimeFormatto(record.getEntranceDate().format(formatter));
        }
        String receiveEndTime = convertDateTimeFormatto(LocalDateTime.now().format(formatter));


        SyncMjEventRecordDataByHk(1, receiveStartTime, receiveEndTime);


    }

    private void SyncMjEventRecordDataByHk(int pageNo, String receiveStartTime, String receiveEndTime) {
        JSONObject recordParams = new JSONObject();
        recordParams.put(PAGE_NO_KEY, pageNo);
        recordParams.put(PAGE_SIZE_KEY, 1000);
        recordParams.put("receiveStartTime", receiveStartTime);
        recordParams.put("receiveEndTime", receiveEndTime);
        recordParams.put("eventTypes", new int[]{196893});//进出有效性
        recordParams.put("sort", "receiveTime");
        recordParams.put("order", "asc");

        XxlJobHelper.log("同步海康门禁人员打卡记录查询条件：{}", recordParams.toJSONString());
        String resultInfo = centerUtilsService.doPost("/api/acs/v2/door/events", recordParams.toJSONString());
        XxlJobHelper.log("同步海康门禁人员打卡记录返回：{}", resultInfo);
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject recordResult = JSON.parseObject(resultInfo);
            JSONObject recordData = recordResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(recordData) && ObjectUtils.isNotEmpty(recordData.getJSONArray("list"))) {
                JSONArray list = recordData.getJSONArray("list");
                buildMjEventData(list);
                if (ObjectUtils.isNotEmpty(list)) {
                    SyncMjEventRecordDataByHk(pageNo + 1, receiveStartTime, receiveEndTime);
                }

            } else {
                XxlJobHelper.log("同步海康门禁人员打卡记录失败");
            }
        }


    }

    @Async
    protected void buildMjEventData(JSONArray list) {
        List<HkEventRecord> eventList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject eventInfo = list.getJSONObject(i);
            eventList.add(new HkEventRecord()
                    .setMjdId(eventInfo.getString("doorIndexCode"))
                    .setMjdNam(eventInfo.getString("doorName"))
                    .setUsrCod(eventInfo.getString("cardNo"))
                    .setUsrNam(eventInfo.getString("personName"))
                    .setUsrIdCard(eventInfo.getString("certNo"))
                    .setEntranceType(1)

                    .setEntranceDate(parse(eventInfo.getString("eventTime").substring(0, 19)
                            .replaceAll("T", " "), "yyyy-MM-dd HH:mm:ss"))
                    .setUpdateTime(parse(eventInfo.getString("receiveTime").substring(0, 19)
                            .replaceAll("T", " "), "yyyy-MM-dd HH:mm:ss"))
                    .setEventId(eventInfo.getString("eventId"))
                    .setEntrance(convertInAndOutType(eventInfo.getInteger("inAndOutType")))
            );
        }
        XxlJobHelper.log("更新打卡记录：{}",eventList.size());
        eventRecordService.saveOrUpdateBatch(eventList);
    }
    public static LocalDateTime parse(String str, String format) {
        log.info("时间格式化:{}", str);
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(str, df);
    }
    private String convertInAndOutType(Integer inAndOutType) {
        if (inAndOutType == 1) {
            return "Y";
        } else if (inAndOutType == 0) {
            return "N";
        } else {
            return "未知";
        }
    }

    /**
     * 时间格式转换-DateTime转String参数
     *
     * @param sourceDateTimeString
     * @return
     */
    private String convertDateTimeFormatto(String sourceDateTimeString) {
        DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        // 解析源日期时间字符串为 LocalDateTime（没有关联时区）
        LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTimeString, sourceFormatter);
        // 使用 ZoneId.of("Asia/Shanghai") 将 LocalDateTime 转换为带有时区的 ZonedDateTime 对象
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
        // 格式化为指定的目标日期时间字符串格式
        String targetDateTimeString = zonedDateTime.format(targetFormatter);

        return targetDateTimeString;
    }








}
